package model.levels;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import model.surface.PathPoint;
import model.surface.PathPointLoader;

import android.content.res.AssetManager;
import android.os.Environment;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * This class is used to operate with the file system, to read and write to JSON
 * files.
 * 
 * @author EvilTeam
 * 
 */
public class LevelLoader {

	/**
	 * Method for reading from a file information needed to load a certain level
	 * in the game.
	 * 
	 * @param assetManager
	 * @param fileName
	 * @return List of points from the screen representing the path on the game
	 *         board.
	 */
	public static List<PathPoint> readLevelFromJsonFile(
			AssetManager assetManager, String fileName) {
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		List<PathPoint> pathArray = new ArrayList<PathPoint>();
		List<PathPointLoader> loaderList = null;
		InputStream is = null;
		BufferedReader reader = null;
		StringBuilder out = new StringBuilder();

		try {
			is = assetManager.open(fileName);
			reader = new BufferedReader(new InputStreamReader(is));
			String line;
			while ((line = reader.readLine()) != null) {
				out.append(line);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		loaderList = gson.fromJson(out.toString(),
				new TypeToken<List<PathPointLoader>>() {
				}.getType());

		for (PathPointLoader loader : loaderList) {
			pathArray.add(new PathPoint(loader));
		}
		return pathArray;
	}

	/**
	 * The method is used only when there is created a new level. The methods
	 * create a new file and writes an information about the path for the level.
	 * 
	 * @param list
	 * @param fileName
	 */
	public static void saveLevelToJsonFile(List<PathPointLoader> list,
			String fileName) {
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String str = gson.toJson(list);

		String root = Environment.getExternalStorageDirectory().toString();
		File myDir = new File(root + "/levels");
		myDir.mkdirs();
		String fname = fileName;
		File file = new File(myDir, fname);
		if (file.exists())
			file.delete();
		try {
			FileOutputStream out = new FileOutputStream(file);
			OutputStreamWriter osw = new OutputStreamWriter(out);
			osw.write(str);
			osw.flush();
			osw.close();
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
